import pymysql
import config


class DB():
    def __init__(self):
        self.db = pymysql.connect(**config.db)

    def get_skill(self, skillStr=""):
        """
        获取技能属性
        params: 
            skillStr: 技能编号列表 [str]
        """
        if skillStr:
            cur = self.db.cursor(pymysql.cursors.DictCursor)

            sql = "SELECT * FROM skill WHERE id IN (%s) ORDER BY id ASC" % skillStr
            cur.execute(sql)

            skill_list = cur.fetchall()

            cur.close()
        else:
            skill_list = []

        return skill_list

    def get_item_row(self, id):
        """
        params: [id] 道具编号
        """
        cur = self.db.cursor(pymysql.cursors.DictCursor)

        sql = "SELECT * FROM item WHERE id=%d" % id
        cur.execute(sql)

        item = cur.fetchone()

        return item

    def get_item_all(self, id_str):
        """
        params:[str] 道具编号字符串以”,“分割
        """
        if len(id_str) == 0:
            return []

        cur = self.db.cursor(pymysql.cursors.DictCursor)

        sql = "SELECT * FROM item WHERE id in (%s)" % id_str
        cur.execute(sql)

        item_list = cur.fetchall()

        return item_list

    def get_floor(self, floor):
        """
        params:[int] 楼层编号
        """
        cur = self.db.cursor(pymysql.cursors.DictCursor)

        sql = "SELECT * FROM layout WHERE id=%d" % floor
        cur.execute(sql)

        floor = cur.fetchone()

        return floor

    def get_monster_list(self, level):
        """
        获取怪物列表
        """
        cur = self.db.cursor(pymysql.cursors.DictCursor)
        sql = "SELECT max(level) as level FROM monster WHERE type=0"
        cur.execute(sql)
        max_level = cur.fetchone()["level"]

        if level > max_level:
            level = max_level

        sql = "SELECT id FROM monster WHERE level>=%d AND level<=%d AND type=0" % (
            level-2, level)
        cur.execute(sql)
        monster = cur.fetchall()

        monster_id = []

        for i in monster:
            monster_id.append(i["id"])

        return monster_id

    def get_boss(self, type):
        """
        获取boss
        """
        cur = self.db.cursor(pymysql.cursors.DictCursor)
        sql = "SELECT id FROM monster WHERE type=%d" % type
        cur.execute(sql)
        boss = cur.fetchone()

        return boss["id"]

    def get_monster(self, monster_id):
        """
        获取怪物信息
        """
        cur = self.db.cursor(pymysql.cursors.DictCursor)
        sql = "SELECT name,level,exp,hp,atk,defense,hit,dod,cri FROM monster WHERE id=%d" % monster_id
        cur.execute(sql)
        monster = cur.fetchone()

        return monster

    def log(self, ip, port,content):
        cur = self.db.cursor()
        sql = "INSERT INTO connect_log (ip, `port`,content) VALUES ('%s','%s','%s')" % (ip, port, content)
        cur.execute(sql)
        self.db.commit()

if __name__ == "__main__":
    db = DB()
    print(db.get_monster_list(99))
